import FormData from 'miniprogram-formdata'
import settle from 'axios/unsafe/core/settle'
import AxiosError from './AxiosError'
function adapter(config) {
	if (config.data instanceof FormData) {
		return new Promise((resolve, reject) => {
			const filePath = config.data.get('file')
			const formData = Object.fromEntries(config.data.entries())
			uni.uploadFile({
				url: config.baseURL + config.url,
				filePath,
				formData,
				name: 'file',
				success: res => settle(resolve, reject, transformResponse(res, config)),
				fail: err => transformError(err, reject, config)
			})
		})
	} else {
		return new Promise((resolve, reject) => {
			uni.request({
				url: config.baseURL + config.url,
				method: config.method || 'GET',
				data: JSON.parse(config.data || '{}'),
				header: config.headers || {},
				success: res => settle(resolve, reject, transformResponse(res, config)),
				fail: err => transformError(err, reject, config)
			})
		})
	}
}

function transformResponse(mpResponse, config) {
	const headers = mpResponse.header || mpResponse.headers
	const status = mpResponse.statusCode || mpResponse.status

	let statusText = ''
	if (status === 200) {
		statusText = 'OK'
	} else if (status === 400) {
		statusText = 'Bad Request'
	}

	const response = {
		data: mpResponse.data,
		status,
		statusText,
		headers,
		config
	}
	return response
}

function transformError(error, reject, config) {
	if (error.errMsg.indexOf('request:fail abort') !== -1) {
		// 请求被取消
		reject(new AxiosError('Request aborted', 'ECONNABORTED', config, ''))
	} else if (error.errMsg.indexOf('timeout') !== -1) {
		// 超时处理
		reject(new AxiosError('timeout of ' + config.timeout + 'ms exceeded', 'ECONNABORTED', config, ''))
	} else {
		// 网络异常
		reject(new AxiosError('Network Error', 'ERR_NETWORK', config, ''))
	}
}

export default adapter
